package cn.hallele.bbts.crawler.service.actions.unionlotto;

import cn.hallele.bbts.core.common.utils.BeanUtil;
import cn.hallele.bbts.core.component.io.BBTSPage;
import cn.hallele.bbts.crawler.common.constants.KafkaConstant;
import cn.hallele.bbts.crawler.dao.cache.LotteryDataCache;
import cn.hallele.bbts.crawler.dao.entity.LotteryDataEntity;
import cn.hallele.bbts.crawler.service.actions.unionlotto.pipeline.UnionLottoPipeline;
import cn.hallele.bbts.crawler.service.actions.unionlotto.processor.UnionLottoProcessor;
import cn.hallele.bbts.crawler.service.bo.LotteryDataBO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Service;
import us.codecraft.webmagic.Spider;

import java.util.List;

/**
 * UnionLottoService0
 *
 * @author anle5
 * @since 2023/12/3 星期日 12:53
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class UnionLottoService {
    private final LotteryDataCache lotteryDataCache;

    /**
     * 启动爬虫
     *
     * @param page     page
     * @param pageSize pageSize
     */
    public void start(int page, int pageSize) {
        page = Math.max(0, page);
        pageSize = Math.max(1, pageSize);

        Spider.create(new UnionLottoProcessor())
                .addUrl(String.format("https://www.cwl.gov.cn/cwl_admin/front/cwlkj/search/kjxx/findDrawNotice?name=ssq&pageNo=%s&pageSize=%s&systemType=PC", page, pageSize))
                .addPipeline(new UnionLottoPipeline())
                .thread(1)
                .start();
    }

    /**
     * kafka监听
     *
     * @param lotteryDataBOS lotteryDataBOS
     */
    @KafkaListener(topics = KafkaConstant.TOPIC_CRAWLER_UNION_LOTTO, groupId = KafkaConstant.GROUP_CRAWLER_CENTER)
    public void unionLottoCrawlerListener(List<LotteryDataBO> lotteryDataBOS) {
        log.error("dataBO: {}", lotteryDataBOS.size());
        lotteryDataCache.saveAll(BeanUtil.transferBeanList(lotteryDataBOS, LotteryDataEntity.class));
    }


    /**
     * 查询数据
     *
     * @param pageNo   pageNo
     * @param pageSize pageSize
     * @return 结果集
     */
    public BBTSPage<List<?>> query(int pageNo, int pageSize) {
        Page<LotteryDataEntity> pageResult = lotteryDataCache.findAll(pageNo, pageSize, null);
        List<LotteryDataBO> lotteryDataBOS = BeanUtil.transferBeanList(pageResult.getContent(), LotteryDataBO.class);
        return BBTSPage.<List<?>>builder()
                .body(lotteryDataBOS)
                .totalNum(pageResult.getTotalElements())
                .totalPages(pageResult.getTotalPages())
                .pageSize(pageSize)
                .pageNo(pageNo)
                .build();
    }
}
